import { updateUserStudentCert } from '../../../api/user'
import { uploadFileName, wxUpload } from '../../../utils/upload'
import { formatTime } from '../../../utils/util'

Page({
  data: {
    studentCertUrls: [],
    studentCertValid: '',
    showTime: false,
    studentCert: {
      authApplyId: null,
      studentCertUrl: '',
      studentCertValid: new Date()
    }
  },

  onLoad: function (options) {
    const studentCert = getApp().globalData.studentCert;
    if (studentCert!==undefined&&studentCert.studentCertValid) {
      console.log('...')
      this.setData({
        studentCert: studentCert,
        studentCertValid: formatTime(studentCert.studentCertValid, '{y}年{m}月{d}日')
      })
    }
    console.log(this.data.studentCert)
  },

  afterRead(event) {
    const _this = this;
    const { file } = event.detail;
    const fileName = uploadFileName(file.path);

    wxUpload({
      biz: 'CERTIFICATE',
      fileName: fileName,
      size: file.size,
      filePath: file.path
    }).then(res => {
      _this.setData({
        studentCertUrls: [{url: res.signatureUrl}],
        'studentCert.studentCertUrl': res.uri
      })
    })
  },

  removeImage(e) {
    this.setData({
      studentCertUrls: [],
      'studentCert.studentCertUrl': ''
    })
  },

  done(e) {
    const pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    updateUserStudentCert(this.data.studentCert).then(res => {
      prevPage.setData({
        'form.studentCert': this.data.studentCert
      })
      wx.navigateBack({
        delta: 1,
      })
    })
  },

  selectTime() {
    this.setData({ showTime: true })
  },

  cancelSelectTime() {
    this.setData({ showTime: false })
  },

  confirmStartTime(e) {
    this.setData({
      'studentCert.studentCertValid': formatTime(e.detail, '{y}-{m}-{d}'),
      studentCertValid: formatTime(e.detail, '{y}年{m}月{d}日'),
      showTime: false
    })
  }

})
